<template>
    <div class="navbar">
        <div class="leftbar">
            <div class="car">购物车</div>
            <div class="adr" @click="toadress">
                <span><van-icon name="location-o" /></span>
                <span v-show="userId" class="adress">{{ adress }}</span>
                <span v-show="!userId">北京市朝阳区望京街道</span>
            </div>
        </div>
        <!-- 分享按钮 -->
        <div>
            <van-cell icon="ellipsis" @click="show = true" />
            <van-action-sheet v-model:show="show" :actions="actions" @select="onSelect" @click="funlist" />
        </div>
    </div>

    <!-- 未登录显示 -->
    <div v-if="!useToken" class="upbo">
        <van-notice-bar color="red" background="#ecf9ff" left-icon="info-o" @click="tologin">
            您还没有登录--<strong>点击登录</strong>
        </van-notice-bar>
        <div class="imgpart">
            <img src="@/assets/images/emptyx2.png" alt="">
            <p>您还没有添加任何商品</p>
        </div>
    </div>

    <!-- 商品列表 -->
    <div v-else="useToken" class="upbo">
        <div v-show="!exhibition">
            <van-checkbox-group v-model="checked" v-for="(item, index) in proList" @click="chose(item)">
                <van-checkbox :name="index">
                </van-checkbox>
                <van-card :num="item.num" :price="item.originprice" :title="item.proname" :key="index" :thumb="item.img1">
                    <template #footer>
                        <van-button size="mini" @click="add(index)"> &nbsp ＋ &nbsp </van-button>
                        <van-button size="mini" @click="reduce(index)">&nbsp － &nbsp</van-button>
                    </template>
                </van-card>
            </van-checkbox-group>

            <div class="btmbox">
                没有更多了哦~~
            </div>
        </div>
        <div v-show="exhibition" class="imgpart">
            <img src="@/assets/images/emptyx2.png" alt="">
            <p>您还没有添加任何商品</p>
        </div>

    </div>

    <!-- 提交订单按钮 -->
    <van-submit-bar :price="total" button-text="提交订单" @submit="onSubmit" :placeholder="true">
        <van-checkbox :checked='flag' @click="tocheck">全选</van-checkbox>
    </van-submit-bar>
</template>

<script setup lang="ts">
import { showToast } from 'vant';
import { onMounted, ref, } from 'vue';
import { useUserInfoStore } from '@/stores/useInfo';
import { useRouter } from 'vue-router';
import { GetCarList, UpdateCart, RemoveCarPro, RemoveAllCar, GetDefaultAds, Addorder, CartSelectone, CartSelectall } from '@/api/api'


const router = useRouter()
const useInfo = useUserInfoStore()
const userId = useInfo.getUserId
const useToken = useInfo.getUserToken
const exhibition = ref(false)
const flag = ref(false)
const show = ref(false)
const proList = ref<any[]>([])//商品列表
const checked = ref<any[]>([])
const total = ref(0)
const thisproid = ref('')
const adress = ref('')



const checkanyone = async (params: any) => {//更新购物车选中状态
    const checkone = await CartSelectone(params)
    console.log(checkone);
}
const checkedall = async (params: any) => {//更新全选状态
    const resall = await CartSelectall(params)
    console.log(resall);
}

const start = async () => {//获取购物车数据
    gettotal()
    const params = { userid: userId }
    const res = await GetCarList(params)
    if (res.data.code === '10020') {
        exhibition.value = true
    } else if (res.data.code === '200') {
        // console.log(res);
        proList.value = res.data.data
        exhibition.value = false
        proList.value.forEach(item => {
            item.flag = false
        })
    }
    console.log(proList.value);

}
onMounted(async () => {//开机自启
    const params = { userid: userId }
    const res = await GetDefaultAds(params)//获取默认地址
    if (res.data.code === '200') {
        if (res.data.data.length != 0) {
            const position = res.data.data[0]
            adress.value = position.province + position.city + position.county + position.addressDetail
        } else {
            adress.value = '北京市朝阳区望京街道'
        }
    }
    start()
    checkedall({
        userid: userId,
        type: false
    })
})
const gettotal = () => {//获取总价
    total.value = 0
    for (let n = 0; n < checked.value.length; n++) {
        let no = checked.value
        let money = proList.value
        total.value += money[no[n]].originprice * money[no[n]].num * 100
    }
}
const chose = (item: any) => {//复选框点击事件
    let arr: any[] = []
    checked.value.forEach(i => {
        arr.push(proList.value[i])
    })
    console.log(item.cartid);
    const resut = arr.filter((t) => {
        return t === item
    })
    if (resut.length != 0) {
        const params = {
            cartid: item.cartid,
            flag: true,
        }
        checkanyone(params)
    } else {
        const params2 = {
            cartid: item.cartid,
            flag: false,
        }
        checkanyone(params2)
    }
    gettotal()
}
const add = async (index: number) => {//添加按钮
    // num.value = proList.value[index].num + 1
    // console.log(num.value);
    proList.value[index].num += 1;
    thisproid.value = proList.value[index].cartid
    const params = {
        cartid: thisproid.value,
        num: proList.value[index].num
    }
    gettotal();
    await UpdateCart(params)//更新数据
    // // console.log(res);
    // start()//添加完成之后更新数据
}
const reduce = async (index: number) => {//减少按钮
    proList.value[index].num -= 1
    gettotal();
    thisproid.value = proList.value[index].cartid
    const params = {
        cartid: thisproid.value,
        num: proList.value[index].num
    }
    await UpdateCart(params)//更新数据
    if (proList.value[index].num === 0) {
        const res2 = await RemoveCarPro({ cartid: thisproid.value })
        if (res2.data.code === '200') {
            showToast({
                message: '删除成功',
                position: 'middle'
            })
        }
    }
    start()//减少完成后更新数据
}
const toggleAll = () => {//反选
    checked.value = []
    checkedall({
        userid: userId,
        type: false
    })
}
const checkAll = () => {//全选
    total.value = 0
    checked.value = []//清空列表  防止二次添加
    for (let i = 0; i < proList.value.length; i++) {
        checked.value.push(i)
        total.value += (Number(proList.value[i].originprice) * Number(proList.value[i].num)) * 100
    }
    if (checked.value.length === proList.value.length) {
        checkedall({
            userid: userId,
            type: true
        })
    }
}
const tocheck = () => {//'全选'按钮点击事件
    if (flag.value === true) {
        flag.value = false
        toggleAll()
        total.value = 0
    } else {
        flag.value = true
        checkAll()
    }
}
const toadress = () => {//跳转到地址页面
    if (userId) {
        router.push('/addres')
    } else {
        router.push('/login')
    }
}
const tologin = () => {//跳转到登录页面
    router.push('/login')
}
const onSelect = (item: any) => {// 默认情况下点击选项时不会自动收起
    // 可以通过 close-on-click-action 属性开启自动收起

    show.value = true;
    showToast(item.name);
};
const funlist = async (actions: any) => {//清空购物车
    if (actions.target.innerHTML === '清空购物车') {
        const params = {
            userid: userId
        }
        const res = await RemoveAllCar(params)
        // console.log(res);
        if (res.data.code = '200') {
            start()
        }
    }
    // console.log(actions.target.innerHTML);

}
const actions = [
    { name: '消息' },
    { name: '搜索' },
    { name: '清空购物车' },
];
const subpro = async () => {//提交订单接口 添加到订单 跳转至订单页面
    if (useToken) {
        const params = {
            userid: userId
        }
        const res = await Addorder(params)
        if (res.data.code === '200') {
            router.push({
                path: '/order',
                query: {
                    time: res.data.time
                }
            })
        }
    } else {
        router.push('/login')
    }
}
const onSubmit = () => {//提交按钮 
    if (checked.value.length > 0) {
        subpro()
    } else {
        showToast({
            message: '未选择任何商品',
            position: 'middle'
        })
    }

}
</script>

<style lang="scss" scoped>
.upbo {
    margin-bottom: 50px;
}

.btmbox {
    height: 100px;
    text-align: center;
    line-height: 100px;
}

.navbar {
    height: 50px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: sticky;
    top: 0;
    z-index: 10000;
    background-color: white;

    .leftbar {
        display: flex;
        width: 80%;

        .adr {
            width: 80%;
            margin-top: 5px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }

        .car {
            width: 70px;
            margin-left: 10px;
            margin-right: 20px;
            font-size: 18px;
            font-weight: 900;
        }
    }
}

.imgpart {
    width: 100%;
    margin-top: 50px;
    text-align: center;

    img {
        display: block;
        margin: 0 auto;
    }
}
</style>